/**
 * Copyright (c) 2018 开源 All rights reserved.
 * <p>
 * https://www.sxyc.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.controller;

import io.renren.annotation.Login;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.Result;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.modules.yckj.common.ThreadLocalUtil;
import io.renren.modules.yckj.dto.InvoiceDTO;
import io.renren.modules.yckj.dto.InvoiceLogsDTO;
import io.renren.modules.yckj.enums.status.CommonStatus;
import io.renren.modules.yckj.enums.status.InvoiceStatus;
import io.renren.modules.yckj.enums.status.PayStatus;
import io.renren.modules.yckj.enums.type.BusinessType;
import io.renren.modules.yckj.service.InvoiceLogsService;
import io.renren.modules.yckj.service.InvoiceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试接口
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/yckj/invoice")
@Tag(name = "发票接口", description = "发票接口")
@AllArgsConstructor
public class ApiInvoiceController {

    private final InvoiceService invoiceService;

    private final InvoiceLogsService invoiceLogsService;

    @Login
    @GetMapping("list")
    @Operation(summary = "获取列表")
    @ApiResponse(content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = InvoiceDTO.class)))
    public Result<List<InvoiceDTO>> list() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", ThreadLocalUtil.getUserId());
        List<InvoiceDTO> dtoList = invoiceService.list(map);
        return new Result<List<InvoiceDTO>>().ok(dtoList);
    }

    @Login
    @PostMapping("save")
    @Operation(summary = "添加")
    public Result<Boolean> save(@RequestBody InvoiceDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        dto.setUserId(ThreadLocalUtil.getUserId());
        dto.setUsername(ThreadLocalUtil.getUserName());
        dto.setCreateTime(new Date());
        dto.setUpdateTime(new Date());
        if (dto.getIsDefault().equals(CommonStatus.YES.getCode())) {
            //把是默认的更新成不是默认
            invoiceService.updateIsDefaultNo(dto.getUserId());
        }
        boolean b = invoiceService.save(dto);

        return new Result<Boolean>().ok(b);
    }

    @Login
    @PostMapping("update")
    @Operation(summary = "修改")
    public Result<Boolean> update(@RequestBody InvoiceDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        InvoiceDTO dbDto = invoiceService.get(dto.getId());
        boolean b = false;
        if (dbDto != null && dbDto.getUserId().equals(ThreadLocalUtil.getUserId())) {
            dto.setUpdateTime(new Date());
            if (dto.getIsDefault().equals(CommonStatus.YES.getCode())) {
                //把是默认的更新成不是默认
                invoiceService.updateIsDefaultNo(dbDto.getUserId());
            }
            b = invoiceService.update(dto);
        }
        return new Result<Boolean>().ok(b);
    }

    @Login
    @GetMapping("delete")
    @Operation(summary = "删除")
    @Parameter(name = "id", description = "主键", required = true)
    public Result<Boolean> delete(@RequestParam("id") Long id) {
        InvoiceDTO dbDto = invoiceService.get(id);
        boolean b = false;
        if (dbDto != null && dbDto.getUserId().equals(ThreadLocalUtil.getUserId()))
            b = invoiceService.deleteById(id);
        return new Result<Boolean>().ok(b);
    }


    @Login
    @GetMapping("logs/page")
    @Operation(summary = "变动明细分页")
    @ApiResponse(content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = InvoiceLogsDTO.class)))
    @Parameters({
            @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", required = true),
            @Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true),
            @Parameter(name = Constant.ORDER_FIELD, description = "排序字段"),
            @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)")
    })
    public Result<PageData<InvoiceLogsDTO>> page(@RequestParam Map<String, Object> params) {
        params.put("userId", ThreadLocalUtil.getUserId());
        params.put("leBusinessType", BusinessType.RECHARGE_TEAM.getCode());
        params.put("geStatus", PayStatus.PAYED.getCode());
        params.put("orderField", "id");
        params.put("order", "desc");
        PageData<InvoiceLogsDTO> page = invoiceLogsService.pageForApi(params);
        return new Result<PageData<InvoiceLogsDTO>>().ok(page);
    }

    @Login
    @PostMapping("logs/apply")
    @Operation(summary = "申请开票  invoiceId,invoiceType,fileType,note")
    public Result<Boolean> getUserRechargeParams(@RequestBody InvoiceLogsDTO invoiceLogsDTO) {
        invoiceLogsDTO.setUserId(ThreadLocalUtil.getUserId());
        invoiceLogsDTO.setUsername(ThreadLocalUtil.getUserName());
        invoiceLogsDTO.setBusinessType(BusinessType.APPLY.getCode());
        invoiceLogsDTO.setStatus(PayStatus.PAYED.getCode());
        invoiceLogsDTO.setCreateTime(new Date());
        invoiceLogsDTO.setUpdateTime(new Date());
        boolean b = invoiceLogsService.save(invoiceLogsDTO);
        return new Result<Boolean>().ok(b);
    }


    @Login
    @GetMapping("logs/opened/page")
    @Operation(summary = "已开发票列表")
    @ApiResponse(content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = InvoiceLogsDTO.class)))
    @Parameters({
            @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", required = true),
            @Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true),
            @Parameter(name = Constant.ORDER_FIELD, description = "排序字段"),
            @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)")
    })
    public Result<PageData<InvoiceLogsDTO>> logsOpenedPage(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
        params.put("userId", ThreadLocalUtil.getUserId());
        params.put("invoiceStatus", InvoiceStatus.INVOICED.getCode());
//        params.put("orderField", "id");
//        params.put("order", "desc");
        PageData<InvoiceLogsDTO> page = invoiceLogsService.pageForApi(params);
        return new Result<PageData<InvoiceLogsDTO>>().ok(page);
    }
}